package work.lianbiao;

import work.ListNode;

public class Problem707 {
    class MyLinkedList {

        int size;
        ListNode head;

        public MyLinkedList() {
            size = 0;
            head = new ListNode(0);
        }

        public int get(int index) {
            if (index < 0 || index >= size) {
                return -1;
            }
            ListNode cur = head;
            for (int i = 0; i <= index; i++) {
                cur = cur.next;
            }
            return cur.val;
        }


        public void addAtHead(int val) {
            ListNode cur = head;
            ListNode temp = new ListNode(val);
            temp.next = cur.next;
            cur.next = temp;
            size++;
        }

        public void addAtTail(int val) {
            ListNode cur = head;
            for (int i = 0; i < size; i++) {
                cur = cur.next;
            }
            ListNode temp = new ListNode(val);
            cur.next = temp;
            size++;
        }

        public void addAtIndex(int index, int val) {
            if (index < 0 || index > size) return;
            ListNode cur = head;
            ListNode temp = new ListNode(val);
            for (int i = 0; i < index; i++) {
                cur = cur.next;
            }
            temp.next = cur.next;
            cur.next = temp;
            size++;
        }

        public void deleteAtIndex(int index) {
            if (index >= size || index < 0) return;
            ListNode cur = head;
            for (int i = 0; i < index; i++) {
                cur = cur.next;
            }
            cur.next = cur.next.next;
            size--;
        }
    }

    public static void main(String[] args) {
        Problem707 problem707 = new Problem707();
        MyLinkedList myLinkedList = problem707.new MyLinkedList();
        myLinkedList.addAtHead(7);
        myLinkedList.addAtHead(2);
        myLinkedList.addAtHead(1);
        myLinkedList.addAtIndex(3, 0);         // 返回 2
        myLinkedList.deleteAtIndex(2);
        myLinkedList.addAtHead(6);
        myLinkedList.addAtTail(4);// 现在，链表变为 1->3
        int i = myLinkedList.get(4);
        System.out.println(i);
        myLinkedList.addAtHead(4);
        myLinkedList.addAtIndex(5, 0);
        myLinkedList.addAtHead(6);
    }
}
